import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
import { Task } from '../../pages/tasklist/task';

/*
  Generated class for the HttpDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Injectable()
export class HttpDataProvider {

  private readonly baseUrl:string='https://api2.bmob.cn/1';//加入一个链接地址只读的地址,计入地址前缀

  private readonly httpOptions:Object={

  headers :new HttpHeaders({

     'X-Bmob-Application-Id': 'd6c61af01ecf7f4cbbea6ac4dd626628',
     'X-Bmob-REST-API-Key': '008ab049eb83daf0bf2ff30ed2d4df03',
     'Content-Type': 'application/json',
  })//头部创建一个对象,都要单引
   
  };//创建一个头部

  constructor(public http: HttpClient) {
    //console.log('Hello HttpDataProvider Provider');//默认启动的服务加载
    console.log('获取HTTP数据服务加载');//增加一个服务
  }


 
  /**
   * 获取待办事项列表
   * @returns{Observable<Task[]>}  待办事项列表集合
   */

  getTaskList(): Observable<Task[]>{
    return this.http.get<Task[]>(`${this.baseUrl}/classes/TODOList`,this.httpOptions).map(data =>data["results"]);
    //第一个用字符模板不是单引而是和~一起的那个,链接之前的数据,
    //利用导入map来映射restapi.ts中运行的result的结果

  }

  
  /**
   * 收尾  获取数据,返回一个Observable对象
   * 获取指定待办事项
   * @param objectId 
   */
  getTask(objectId: string): Observable<Task>{
    return this.http.get<Task>(`${this.baseUrl}/classes/TODOList/${objectId}`,this.httpOptions);
    //不需要数组和map
  }

  /**
   * 新增待办事项
   * @param task
   * @returns{Observable<Task[]>}响应结果 
   */
   addTask(task:Task):Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.post<Task>(`${this.baseUrl}/classes/TODOList/`,_task,this.httpOptions);
   }

/**
 * 更新指定待办事项
 * @param task 
 * @returns{Observable<Task[]>}响应结果
 */
  updateTask(task: Task):Observable<Task>{
    let _task={title:task.title,status:task.status,description:task.description};
    return this.http.put<Task>(`${this.baseUrl}/classes/TODOList/${task.objectId}`,_task,this.httpOptions);
  }
  /**
   * 删除指定的待办事项，在BMOb删除
   */

   deleteTask(task:Task):Observable<{}>{
     return this.http.delete(`${this.baseUrl}/classes/TODOList/${task.objectId}`,this.httpOptions);
   }
} //获取所有的值
